<template>
  <div class="school pad">
    <div class="head">
      <span>学校管理</span>
      <el-button circle icon="el-icon-plus" type="success" @click="openAddDialog"></el-button>
    </div>
    <!-- <bar-chart :chartData="schoolChartData" :options="barOptions" :height="200"></bar-chart> -->
    <div class="school-chart" ref="schoolChart"></div>

    <el-input
      class="m-t-b"
      v-model="searchText"
      placeholder="输入学校名称关键字搜索, 例如: 财经"
      clearable
      @input="clearSearch"
    >
      <el-button
        icon="el-icon-search"
        type="success"
        @click="handleSearch"
        slot="append"
      ></el-button>
    </el-input>
    <el-table :data="schoolList" border stripe v-loading="loading" style="margin-top: 10px;">
      <el-table-column label="学校名称" prop="schoolTitle"></el-table-column>
      <el-table-column label="学校标识" prop="schoolCode"></el-table-column>
      <el-table-column label="所属省" prop="province"></el-table-column>
      <el-table-column label="所属市" prop="city"></el-table-column>
      <el-table-column label="学校类型">
        <template slot-scope="scopes">
          {{scopes.row.schoolType | schoolTypeFilter}}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createDate"></el-table-column>
      <el-table-column label="操作" fixed="right" width="180">
        <template slot-scope="scopes">
          <el-button circle type="info" icon="el-icon-edit" @click="openEditDialog(scopes.row)"></el-button>
          <el-button circle type="primary" icon="el-icon-setting" @click="goSetting(scopes.row)" title="设置量表"></el-button>
          <el-button circle type="danger" icon="el-icon-delete" @click="deleteSchool(scopes.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      class="flex m-t-b"
      :page-size="pageSize"
      layout="prev, pager, next"
      @current-change="handlePagi"
      :total="schoolTotal">
    </el-pagination>
    <el-dialog :visible.sync="showSchoolDialog">
      <el-form :model="school" label-position="top" ref="school" :rules="rules">
        <el-form-item label="学校名称" prop="schoolTitle">
          <el-input v-model="school.schoolTitle" />
        </el-form-item>
        <el-form-item label="学校标识" prop="schoolCode">
          <el-input v-model="school.schoolCode" />
        </el-form-item>
        <el-form-item label="学校所属省" prop="provinceId">
          <el-select v-model="school.provinceId" @change="changeProvince">
            <el-option
              v-for="item in provinceList"
              :key="item.id"
              :value="item.id"
              :label="item.cname"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学校所属市" prop="cityId">
          <el-select v-model="school.cityId">
            <el-option
              v-for="item in cityList"
              :key="item.id"
              :value="item.id"
              :label="item.cname"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学校类型" prop="schoolType">
          <el-select v-model="school.schoolType">
            <el-option
              v-for="item in schoolTypes"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideSchoolDialog">取 消</el-button>
        <el-button type="primary" @click="fetchAddSchool('school')" :loading="isDoing">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showChartDialog" title="设置量表">
      <!-- <div>设置量表</div> -->
      <el-form ref="schoolChart" :model="schoolChart" label-position="top">
        <el-form-item label="选择量表">
          <el-select v-model="schoolChart.chartId">
            <el-option></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="hideChartDialog">取 消</el-button>
        <el-button type="primary" :disabled="isRequesting" @click="addSchoolChart('schoolChart')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getAllArea,
  addSchool,
  updateSchool,
  getSchoolList,
  deleteSchoolById,
  getSchoolChartData
} from '../api/hospitalAPI';
import { formatDate } from '../util';
// import BarChart from '../components/BarChart.vue';
export default {
  name: 'School',
  data () {
    return {
      showChartDialog: false,
      isRequesting: false,
      schoolChart: {
        chartId: ''
      },
      schoolList: [],
      provinceList: [],
      cityList: [],
      school: {
        schoolTitle: '',
        schoolCode: '',
        provinceId: '',
        cityId: '',
        schoolType: ''
      },
      searchText: '',
      schoolDialogTitle: '添加学校',
      showSchoolDialog: false,
      isDoing: false,
      schoolTypes: [
        { value: 1, label: '幼儿园' },
        { value: 2, label: '小学' },
        { value: 3, label: '中学' },
        { value: 4, label: '高中' },
        { value: 5, label: '大学' }
      ],
      loading: true,
      schoolTotal: 0,
      pageSize: 10,
      curSchoolId: '',
      schoolChartData: {},
      barOptions: {
        // tooltip: {
        //   filter () {
        //     console.log(arguments);
        //     return 1
        //   }
        // }
      },
      rules: {
        schoolTitle: [
          { required: true, message: '学校名称不能为空!', trigger: 'blur' }
        ],
        schoolCode: [
          { required: true, message: '学校标识不能为空!', trigger: 'blur' }
        ],
        provinceId: [
          { required: true, message: '学校所属省不能为空!', trigger: 'blur' }
        ],
        cityId: [
          { required: true, message: '学校所属市不能为空!', trigger: 'blur' }
        ],
        schoolType: [
          { required: true, message: '学校类型不能为空!', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    // BarChart
  },
  methods: {
    fetchAreaById (id) { // 根据id查询地区
      getAllArea(id)
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data || [];
          if (id === 1) {
            this.provinceList = list
          } else {
            this.cityList = list
          }
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    goSetting (row) { // 进入设置量表页面
      console.log(row);
      this.showChartDialog = true
    },
    renderSchoolChart (data) { // 渲染学校表格
      console.log(data);
      const schoolChart = this.$echarts.init(this.$refs.schoolChart);
      console.log(schoolChart);
      let option = {
        title: {
          text: "学校省份分布图"
        },
        xAxis: {
          type: 'category',
          data: data.labels
        },
        yAxis: {
          type: 'value'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        series: [
          {
            name: "学校数量",
            type: "bar",
            data: data.data
          }
        ]
      };
      schoolChart.setOption(option)
    },
    openAddDialog () { // 打开新增学校弹出框
      this.school.schoolTitle = '';
      this.school.schoolCode = '';
      this.school.provinceId = '';
      this.school.cityId = '';
      this.school.schoolType = '';
      this.cityList = [];
      this.schoolDialogTitle = '添加学校';
      this.showSchoolDialog = true
    },
    changeProvince (e) { // 切换省
      this.cityList = [];
      this.school.cityId = '';
      this.fetchAreaById(Number(e))
    },
    hideSchoolDialog () { // 隐藏学校弹出框
      this.showSchoolDialog = false
    },
    fetchAddSchool (name) { // 添加学校
      this.$refs[name].validate(valid => {
        if (valid) {
          this.isDoing = true;
          if (this.schoolDialogTitle === '添加学校') {
            addSchool(this.school)
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                });
                this.fetchSchoolChartData();
                this.fetchSchoolList(1);
                this.showSchoolDialog = false
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              };
              this.isDoing = false
            })
            .catch(e => {
              this.isDoing = false;
              this.$message.error('服务异常!')
            })      
          } else {
            updateSchool({
              ...this.school,
              schoolId: this.curSchoolId
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message.success('修改成功!');
                this.fetchSchoolChartData();
                this.showSchoolDialog = false;
                this.fetchSchoolList(1)
              } else {
                this.$message.error(res.data.msg || '服务异常!')
              };
              this.isDoing = false
            })
            .catch(e => {
              this.isDoing = false;
              this.$message.error('服务异常!')
            })
          }
        } else {
          return false
        }
      })
    },
    fetchSchoolList (index) { // 分页查询学校
      this.loading = true;
      getSchoolList({
        index,
        count: this.pageSize,
        queryParam: {
          schoolTitle: this.searchText || null
        }
      })
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data.list || [];
          list.forEach(item => {
            item.createDate = formatDate(item.createDate, 'zh:')
          });
          this.schoolList = list;
          this.schoolTotal = res.data.data.totalRecord || 0;
          console.log(list)
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        };
        this.loading = false
      })
      .catch(e => {
        this.loading = false;
        this.$message.error('服务异常!')
      })
    },
    openEditDialog (row) { // 打开编辑学校弹出框
      this.fetchAreaById(Number(row.provinceId));
      this.school.schoolTitle = row.schoolTitle;
      this.school.schoolCode = row.schoolCode;
      this.school.provinceId = Number(row.provinceId);
      this.school.cityId = Number(row.cityId);
      this.school.schoolType = Number(row.schoolType);
      this.schoolDialogTitle = '修改学校';
      this.curSchoolId = Number(row.schoolId);
      this.showSchoolDialog = true
    },
    deleteSchool (row) { // 删除学校
      this.$confirm(`确定永久删除学校: ${row.schoolTitle}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        deleteSchoolById(row.schoolId)
        .then(res => {
          if (res.data.code === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.fetchSchoolChartData();
            this.fetchSchoolList(1)
          } else {
            this.$message.error(res.data.msg || '服务异常!')
          }
        })
        .catch(e => {
          this.$message.error('服务异常!')
        })
      })
      .catch(e => {
        this.$message({
          type: 'info',
          message: '取消删除'
        })
      })
    },
    handlePagi (page) { // 学校分页
      this.fetchSchoolList(page)
    },
    handleSearch () { // 搜索事件
      if (!this.searchText.trim()) {
        return this.$message.info('请输入搜索内容')
      };
      this.fetchSchoolList(1)
    },
    clearSearch () { // 清除搜索
      if (!this.searchText.trim()) {
        this.fetchSchoolList(1)
      }
    },
    fetchSchoolChartData () { // 获取学校统计数据
      getSchoolChartData()
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data || [];
          let labels = [];
          let datas = [];
          const data1 = [];
          list.forEach(item => {
            labels.push(item.province);
            datas.push(item.number);
            data1.push(item.number)
          });
          this.schoolChartData = {
            labels,
            datasets: [
              {
                label: '学校数量省份分布图',
                backgroundColor: '#fab1a0',
                data: datas
              }
            ]
          };
          const schoolData = {
            labels,
            data: data1
          };
          this.renderSchoolChart(schoolData)
          console.log(schoolData)
          // console.log(this.schoolChartData)
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        console.log(e)
        this.$message.error('服务异常!')
      })
    },
    hideChartDialog () { // 隐藏表格弹出框
      this.showChartDialog = false
    },
    addSchoolChart () { // 添加学校量表
      console.log(this.schoolChart)
    },

  },
  filters: {
    schoolTypeFilter (type) {
      let res = '';
      switch (type) {
        case '1':
          res = '幼儿园';
          break
        case '2':
          res = '小学';
          break
        case '3':
          res = '中学';
          break
        case '4':
          res = '高中';
          break
        case '5':
          res = '大学';
          break
        default:
          break
      };
      return res
    }
  },
  created () {
    this.fetchSchoolChartData();
    this.fetchAreaById(1);
    this.fetchSchoolList(1);
  }
}
</script>
<style lang="scss">
  .school {
    .school-chart {
      height: 400px;
    }
  }
</style>
